package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.AppUserLoginMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author lo
 * @date 2021/9/28
 */
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<AppUserLoginMapper, ApUser> implements ApUserLoginService {
    /**
     * app端登录实现
     * @param dto 设备,手机号,密码
     * @return 统一参数
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        //1.校验参数
        if (dto.getEquipmentId() == null){
         return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"设备编号不能为空");
        }

        //2.不登录
        HashMap<String, Object> map = new HashMap<>(8);
        if (dto.getEquipmentId() == 0){
            //说明是不登录,创建token存储id为0
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        //3.用户登录
        if (Strings.isBlank(dto.getPassword()) ||Strings.isBlank(dto.getPhone())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名和密码不能为空");
        }
        //4.校验用户名和密码
        //状态为0的用户为正常状态
        ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getPhone, dto.getPhone())
                .eq(ApUser::getStatus,0));
        if (apUser == null){
            //说明该用户不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
        //5.校验密码
        String password = apUser.getPassword();
        String dtoPassword = dto.getPassword();
        String asHex = DigestUtils.md5DigestAsHex((dtoPassword + apUser.getSalt()).getBytes());
        if (!password.equals(asHex)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //6.密码正确,颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
        map.put("token",token);
        map.put("user",apUser);
        return ResponseResult.okResult(map);
    }
}
